import * as ElementPlus from 'element-plus';

const ToolUni = {
	toPage(url, data) {
		if (!url) {
			return;
		}
		uni.setStorageSync("ntd_current_url", url);
		if (url.indexOf('http') === 0) {
			return window.open(url)
		}
		if (url.indexOf('/') !== 0 && url.indexOf('.') !== 0) {
			url = '/' + url;
		}
		let prefix = url.indexOf('?') < 0 ? "?" : "&";
		if (data) {
			uni.setStorageSync('ntd_data', data);
			url += `${prefix}ntd_data=${JSON.stringify(data)}`;
		}
		uni.navigateTo({
			url
		});
	},
	storage(key, val) {
		if (!key) return;
		if (val === null) return uni.removeStorageSync(key);
		if (val === undefined) return uni.getStorageSync(key);
		uni.setStorageSync(key, val);
	},
	getCurrentUrl() {
		return uni.getStorageSync("ntd_current_url");
	},
	toBack() {
		uni.navigateBack({
			delta: 1
		});
	},
	toast(message, icon = "none") {
		// uni.showToast({
		// 	message,
		// 	icon
		// })
		ElementPlus.ElMessage({
			showClose: true,
			grouping: true,
			message,
		})
	},
	page() {
		let currentRoutes = getCurrentPages(); // 获取当前打开过的页面路由数组
		let route = currentRoutes[currentRoutes.length - 1].route //获取当前页面路由
		let param = currentRoutes[currentRoutes.length - 1].options; //获取路由参数
		let fullPath = currentRoutes[currentRoutes.length - 1].$page.fullPath; //获取路由参数
		return {
			route,
			param,
			fullPath
		};
	},
	confirm(content = '请确认操作？', title = '') {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title,
				content,
				success: function(res) {
					if (res.confirm) {
						resolve();
					}
				}
			})
		})
	},
	addressSelect() {
		return new Promise((resolve, reject) => {
			uni.authorize({
				scope: 'scope.address',
				success() {
					uni.chooseAddress({
						success: resolve
					})
				}
			})
		});
	},
	headerTop() {
		return document.getElementsByTagName('uni-page-head')[0].offsetHeight;
	},
	share(data = { // 仅适用于App分享
		provider: 'weixin',
		scene: 'WXSceneSession',
		type: 0,
		summary: '摘要信息',
		imageUrl: '',
		href: '/pages/index/index',
		title: '标题'
	}) {
		console.log('开始分享！')
		uni.share({
			success: ret => {
				console.log(JSON.stringify(ret));
			},
			...data
		});
	},
	login() {
		return new Promise((resolve, reject) => {
			uni.login({
				provider: uni.getProvider(),
				success(res) {
					resolve(res);
				},
				fail(err) {
					ToolUni.toast('微信登录失败');
					reject(new Error('微信登录失败'));
				}
			})
		});
	},
	topWindow(option) {
		if (!option) {
			return uni.getTopWindowStyle();
		}
		uni.setTopWindowStyle(Object.assign({
			display: "block"
		}, option));
	},
	leftWindow(option) {
		if (!option) {
			return uni.getLeftWindowStyle();
		}
		uni.setLeftWindowStyle(Object.assign({
			display: "block"
		}, option));
	},
	hideWindow() {
		ToolUni.leftWindow({
			display: "none"
		});
		ToolUni.topWindow({
			display: "none"
		});
	}
}

export default ToolUni;
